package com.sm.chatinputlibrary;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scorpio.baselibrary.PoorApplication;
import com.scorpio.baselibrary.ScreenAdapterTools;
import com.scorpio.baselibrary.utils.PermissionUtils;
import com.scorpio.baselibrary.utils.SoftKeyboardUtil;
import com.scorpio.baselibrary.utils.ViewController;
import com.sm.chatinputlibrary.emoji.EmojiBean;
import com.sm.chatinputlibrary.emoji.EmojiManager;
import com.sm.chatinputlibrary.emoji.EmojiPageAdapter;
import com.sm.chatinputlibrary.emoji.EmojiParser;
import com.sm.chatinputlibrary.emoji.EmojiView;
import com.scorpio.baselibrary.utils.permission.OnPermission;
import com.scorpio.baselibrary.utils.permission.ScorpioPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * created by 包子 on 2019/3/1
 */
public class ChatInput extends LinearLayout implements View.OnClickListener, EmojiPageAdapter.OnItemEmojiChildClickListener, BaseQuickAdapter.OnItemChildClickListener {
    public static final int FUNCTION_FACE = 1;//表情
    public static final int FUNCTION_VOICE = 2;//录音
    public static final int FUNCTION_EXTENDED = 4;//扩展功能

    public static final int FUNCTION_ALL = FUNCTION_FACE | FUNCTION_VOICE | FUNCTION_EXTENDED;

    private EditText chat_send_message;
    private ViewController v;
    private float mEmojiSize = 60;
    private EmojiView mEmojiView;
    private AudioRecorderView chat_recording_btn;
    private ChatFunctionAdapter adapter;
    private List<ChatFunctionBean> mFunctionBeans = new ArrayList<>();
    private int inputMaxLength = 1024;
    private OnChatInputEventListener onChatInputEventListener;
    // 拍照的照片的存储位置
    private String mTempPhotoPath;
    // 照片所在的Uri地址
    private Uri imageUri;
    private int mFunction = 0;
    private ChatInputResultFragment mChatInputResultFragment;

    public ChatInput(Context context) {
        this(context, null);
    }

    public ChatInput(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ChatInput(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View.inflate(context, R.layout.input_layout_chat_input, this);
        v = new ViewController(context, this);
        v.addOnClickListener(this, R.id.chat_emoji_btnt, R.id.chat_send_btn, R.id.chat_extended_btnt, R.id.chat_voice);
        mEmojiView = v.getView(R.id.chat_emoji_layout);
        chat_recording_btn = v.getView(R.id.chat_recording_btn);
        mEmojiView.setOnItemEmojiChildClickListener(this);
        chat_send_message = v.getView(R.id.chat_send_message);
        chat_send_message.setOnClickListener(this);
        chat_send_message.addTextChangedListener(mTextWatcher);
        chat_send_message.setOnFocusChangeListener(onFocusChangeListener);
        if (attrs != null) {
            final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ChatInput);
            mEmojiSize = a.getDimension(R.styleable.ChatInput_emoji_size, mEmojiSize);
            inputMaxLength = a.getInteger(R.styleable.ChatInput_inputMaxLength, inputMaxLength);
            mFunction = a.getInt(R.styleable.ChatInput_function, mFunction);
        }
        //适配自定义参数
        mEmojiSize = ScreenAdapterTools.getInstance().loadCustomAttrValue((int) mEmojiSize);
        mFunctionBeans.add(new ChatFunctionBean(R.drawable.input_icon_photograph, R.string.string_900123));
        mFunctionBeans.add(new ChatFunctionBean(R.drawable.input_icon_uploading_image, R.string.string_900124));
        mFunctionBeans.add(new ChatFunctionBean(R.drawable.input_icon_uploading_file, R.string.string_900125));
        v.setRecyclerViewAdapter(R.id.chat_function_recycler, adapter = new ChatFunctionAdapter(mFunctionBeans))
                .setRecyclerViewLayoutManager(R.id.chat_function_recycler, new GridLayoutManager(context, 4));
        adapter.setOnItemChildClickListener(this);
        initConfig();
        initResultFragment();
    }

    @Override
    public IBinder getWindowToken() {
        return chat_send_message.getWindowToken();
    }

    public EditText getChatEditText() {
        return chat_send_message;
    }

    private void initConfig() {
        setEtCoustomLength(inputMaxLength);
        v.setGone(R.id.chat_emoji_btnt, false);
        v.setGone(R.id.chat_voice, false);
        v.setGone(R.id.chat_extended_btnt, false);
        if (isShowFunction(FUNCTION_FACE)) {
            v.setGone(R.id.chat_emoji_btnt, true);
        }
        if (isShowFunction(FUNCTION_VOICE)) {
            v.setGone(R.id.chat_voice, true);
        }
        if (isShowFunction(FUNCTION_EXTENDED)) {
            v.setGone(R.id.chat_extended_btnt, true);
        }
        openEmojeLayout(false);
        openFunctionLayout(false);
        openRecordingLayout(false);
    }

    private boolean isShowFunction(int fTag) {
        int c = 0;
        int flag = fTag;
        while ((flag & 1) == 0) {
            c++;
            flag >>= 1;
        }
        return ((mFunction & fTag) >> c) == 1;
    }


    //初始化请求的fragment
    private void initResultFragment() {
        if (mChatInputResultFragment == null) {
            mChatInputResultFragment = new ChatInputResultFragment();
            mChatInputResultFragment.prepareRequest((FragmentActivity) getContext(), onChatInputResultListener);
        }
    }

    private void setEtCoustomLength(int length) {
        if (length > 0) {
            chat_send_message.setFilters(new InputFilter[]{new InputFilter.LengthFilter(length)});
        }
    }

    //输入框监听
    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            EmojiManager.getInstance().replaceWithImages(getContext(), chat_send_message.getText(), mEmojiSize);
        }

        @Override
        public void afterTextChanged(Editable s) {
            showSendBtn(s.length() > 0);
        }
    };

    private void showSendBtn(boolean show) {
        v.setEnabled(R.id.chat_send_btn, show);
        v.setGone(R.id.chat_send_btn, show);
        if (isShowFunction(FUNCTION_EXTENDED))
            v.setGone(R.id.chat_extended_btnt, !show);
    }

    //获取焦点的时候
    private OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                SoftKeyboardUtil.dealInputMethod(false, v, getContext());
            }
            if (hasFocus && mEmojiView.getVisibility() == VISIBLE) {
                openEmojeLayout(false);
            }
        }
    };

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.chat_send_message) {
            openEmojeLayout(false);
        } else if (i == R.id.chat_send_btn) {
            if (onChatInputEventListener != null) {
                boolean isClear = onChatInputEventListener.onChatMessage(chat_send_message.getText().toString());
                if (isClear) chat_send_message.setText("");
            } else {
                chat_send_message.setText("");
            }
        } else if (i == R.id.chat_emoji_btnt) {
            openEmojeLayout(!(this.v.getView(R.id.chat_emoji_layout).getVisibility() == VISIBLE));
        } else if (i == R.id.chat_extended_btnt) {
            openFunctionLayout(!(this.v.getView(R.id.chat_function_recycler).getVisibility() == VISIBLE));
        } else if (i == R.id.chat_voice) {
            List<String> permissions = new ArrayList<>();
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            permissions.add(Manifest.permission.RECORD_AUDIO);
            if (PermissionUtils.hasPermissionAndOpen(getContext(), permissions, 0, 0)) {

            }
            ScorpioPermissions.with((Activity) getContext())
                    .permission(Manifest.permission.RECORD_AUDIO
                            , Manifest.permission.WRITE_EXTERNAL_STORAGE
                            , Manifest.permission.READ_EXTERNAL_STORAGE)
                    .request(new OnPermission() {
                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            if (isAll) {
                                openRecordingLayout(!(ChatInput.this.v.getView(R.id.chat_recording_btn).getVisibility() == VISIBLE));
                            }
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            PoorApplication.getInstance().showToast((Activity) getContext(), getContext().getString(R.string.string_900126));
                            if (quick) {
                                ScorpioPermissions.gotoPermissionSettings(getContext(), true);
                            }
                        }
                    });
        }
    }

    public void setOnChatInputEventListener(OnChatInputEventListener onChatInputEventListener) {
        this.onChatInputEventListener = onChatInputEventListener;
    }

    public void setOnAudioRecorderEventListener(AudioRecorderView.OnAudioRecorderEventListener onAudioRecorderEventListener) {
        chat_recording_btn.setOnAudioRecorderEventListener(onAudioRecorderEventListener);
    }

    @Override
    public void onItemChildClick(EmojiBean bean) {
        if (bean != null) {
            SpannableString spannableString = EmojiParser.getInstance(getContext()).addFace(getContext(), bean.getResourcePath(), bean.getEmojiAlias());
            chat_send_message.append(spannableString);
        } else {
            int selection = chat_send_message.getSelectionStart();
            String text = chat_send_message.getText().toString();
            if (selection > 0) {
                String text2 = text.substring(selection - 1);
                if ("]".equals(text2)) {
                    int start = text.lastIndexOf("[");
                    int end = selection;
                    chat_send_message.getText().delete(start, end);
                    return;
                }
                chat_send_message.getText().delete(selection - 1, selection);
            }
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        ChatFunctionBean bean = mFunctionBeans.get(position);
        if (bean.string_id == R.string.string_900123) {//第二个参数是需要申请的权限
            ScorpioPermissions.with((Activity) getContext())
                    .permission(Manifest.permission.CAMERA
                            , Manifest.permission.WRITE_EXTERNAL_STORAGE
                            , Manifest.permission.READ_EXTERNAL_STORAGE)
                    .request(new OnPermission() {
                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            if (isAll) {
                                takePhoto();
                            }
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            PoorApplication.getInstance().showToast((Activity) getContext(), getContext().getString(R.string.string_900126));
                            if (quick) {
                                ScorpioPermissions.gotoPermissionSettings(getContext(), true);
                            }
                        }
                    });
        } else if (bean.string_id == R.string.string_900124) {
            ScorpioPermissions.with((Activity) getContext())
                    .permission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    .request(new OnPermission() {
                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            if (isAll) {
                                choosePhoto();
                            }
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            PoorApplication.getInstance().showToast((Activity) getContext(), getContext().getString(R.string.string_900126));
                            if (quick) {
                                ScorpioPermissions.gotoPermissionSettings(getContext(), true);
                            }
                        }
                    });
        } else if (bean.string_id == R.string.string_900125) {
            ScorpioPermissions.with((Activity) getContext())
                    .permission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    .request(new OnPermission() {
                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            if (isAll) {
                                openFile();
                            }
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            PoorApplication.getInstance().showToast((Activity) getContext(), getContext().getString(R.string.string_900126));
                            if (quick) {
                                ScorpioPermissions.gotoPermissionSettings(getContext(), true);
                            }
                        }
                    });
        }
    }

    //打开语音
    private void openRecordingLayout(boolean visible) {
        v.setGone(R.id.chat_send_message, !visible);
        v.setGone(R.id.chat_recording_btn, visible);
        v.setGone(R.id.chat_emoji_layout, false);
        v.setGone(R.id.chat_function_recycler, false);
        v.setImageDrawable(R.id.chat_emoji_btnt, R.drawable.input_icon_chat_emoji);
        SoftKeyboardUtil.dealInputMethod(false, chat_send_message, getContext());
    }

    //打开扩展功能
    private void openFunctionLayout(boolean visible) {
        v.setGone(R.id.chat_function_recycler, visible);
        v.setGone(R.id.chat_emoji_layout, false);
        v.setImageDrawable(R.id.chat_emoji_btnt, R.drawable.input_icon_chat_emoji);
        SoftKeyboardUtil.dealInputMethod(false, chat_send_message, getContext());
    }

    //打开表情
    private void openEmojeLayout(boolean visible) {
        this.v.setGone(R.id.chat_emoji_layout, visible);
        v.setGone(R.id.chat_function_recycler, false);
        v.setGone(R.id.chat_send_message, true);
        v.setGone(R.id.chat_recording_btn, false);
        v.setImageDrawable(R.id.chat_emoji_btnt, visible ? R.drawable.input_icon_keyboard_pressed : R.drawable.input_icon_chat_emoji);
        SoftKeyboardUtil.dealInputMethod(!visible, chat_send_message, getContext());
    }

    //拍照实现方法
    private void takePhoto() {
        // 跳转到系统的拍照界面
        Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + String.format("photo.jpg");
        imageUri = Uri.fromFile(new File(mTempPhotoPath));
        //下面这句指定调用相机拍照后的照片存储的路径
        intentToTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        mChatInputResultFragment.startActivityForResult(intentToTakePhoto, ChatInputResultFragment.CAMERA_REQUEST_CODE);
    }

    //打开相册方法实现
    private void choosePhoto() {
        Matisse.from(mChatInputResultFragment)
                .choose(MimeType.of(MimeType.JPEG, MimeType.PNG))
                .countable(true)
                .maxSelectable(9)
//                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(ChatInputResultFragment.GALLERY_REQUEST_CODE);
    }

    private void openFile() {

    }

    private OnChatInputResultListener onChatInputResultListener = new OnChatInputResultListener() {
        @Override
        public void onCameraResult() {
            List<Uri> uris = new ArrayList<>();
            uris.add(imageUri);
            if (onChatInputEventListener != null) {
                onChatInputEventListener.onSelectedPicture(uris);
            }
        }

        @Override
        public void onPictureResult(List<Uri> uris) {
            if (onChatInputEventListener != null) {
                onChatInputEventListener.onSelectedPicture(uris);
            }
        }

        @Override
        public void onFileResult() {

        }
    };


    public interface OnChatInputEventListener {
        /**
         * @param message
         * @return true 清理输入框
         */
        boolean onChatMessage(String message);

        /**
         * 选择图片
         *
         * @param uri
         */
        void onSelectedPicture(List<Uri> uri);

        /**
         * 选择文件
         *
         * @param path
         */
        void onSelectedFile(String path);
    }

}
